﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using DLULearningNetworkModel;

namespace DLULearningNetwork.Libs
{
    public class StringHelper
    {
        public static bool IsEmpty(string str)
        {
            return str.Trim().Length == 0;
        }

        public static bool IsEmail(string str)
        { 
            string matchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
             + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
             + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
             + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
            Regex regex = new Regex(matchEmailPattern);
            return regex.IsMatch(str);
        }

        public static string EncodeMD5(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] data = Encoding.ASCII.GetBytes(str);
            data = md5.ComputeHash(data);
            return BitConverter.ToString(data);
        }

        /*--------------Password Generator---------*/
        private static char[] characterArray = "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

        private static Random randNum = new Random();

        static char GetRandomCharacter()
        {
            return characterArray[(int)((characterArray.GetUpperBound(0) + 1) * randNum.NextDouble())];
        }

        /// <summary>
        /// Generate random string
        /// </summary>
        /// <param name="len">lenght of string need to generate</param>
        /// <returns>random string with lenght is 'len'</returns>
        public static string GenerateRandomString(int len)
        {
            StringBuilder sb = new StringBuilder();
            sb.Capacity = len;
            for (int count = 0; count <= sb.Capacity - 1; count++)
            {
                sb.Append(GetRandomCharacter());
            }

            if ((sb != null))
            {
                return sb.ToString();
            }

            return "123ABC";
        }

        public static string StripHTML(string HTMLText)
        {
            var reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
            return reg.Replace(HTMLText, "");
        }

        public static string ShortcutContent(string content, int maxLength)
        {
            string stripHTMLString = StripHTML(content);
            if (stripHTMLString.Length > maxLength)
            {
                return stripHTMLString.Substring(0, Math.Min(stripHTMLString.Length, maxLength)) + " ...";
            }
            else
            {
                return stripHTMLString;
            }
        }

        public static string GetGuidFromContent(string content)
        {
            try
            {
                return content.Substring(0, content.IndexOf("|"));
            }
            catch
            {
                return "";
            }
        }

        public static string GetContentFromContent(string content)
        {
            try
            {
                return content.Substring(content.IndexOf("|") + 1);
            }
            catch
            {
                return "";
            }
        }

        public static int GetLengthOfContent(string content)
        {
            return HttpUtility.HtmlDecode(content).Replace("&amp;","&").Replace("&nbsp", " ").Replace("&gt;", ">").Replace("&lt;", "<").Length;
        }

        public static string GetImageUrl(string urlAvatar, int i)
        {
            if (string.IsNullOrEmpty(urlAvatar))
            {
                return "../../Content/Images/avatar.gif";
            }
            switch (i)
            { 
                case 1:
                    return urlAvatar.Replace("Original", "Small");
                case 2:
                    return urlAvatar.Replace("Original", "Large");
                case 3:
                    return urlAvatar;
            }
            return "../../Content/Images/avatar.gif";
        }

        public static MvcHtmlString GetHtmlAccountName(Account account,string onclickHandler = "")
        {
            if (string.IsNullOrEmpty(onclickHandler))
            {
                return MvcHtmlString.Create(string.Format(" <a  href='/UserPage/UserHome/{0}'>{1}</a>", account.Nickname_s, account.FirstName_s));
            }
            else
            {
                return MvcHtmlString.Create(string.Format(" <a  href='/UserPage/UserHome/{0}' {3}>{1}</a>", account.Nickname_s, account.FirstName_s,onclickHandler));
            }
        }

        public static MvcHtmlString GetHtmlAccountFullName(Account account, string onclickHandler = "")
        {
            if (string.IsNullOrEmpty(onclickHandler))
            {
                return MvcHtmlString.Create(string.Format(" <a  href='/UserPage/UserHome/{0}' style='color:green;'>{1}</a>", account.Nickname_s, account.LastName_s + " " + account.FirstName_s));
            }
            else
            {
                return MvcHtmlString.Create(string.Format(" <a  href='/UserPage/UserHome/{0}' {3} style='color:green;'>{1}</a>", account.Nickname_s, account.LastName_s + " " + account.FirstName_s, onclickHandler));
            }
        }

        public static MvcHtmlString GetHtmlCourseName(Course course,string onclickHandler ="")
        {
            if (string.IsNullOrEmpty(onclickHandler))
            {
                return MvcHtmlString.Create(string.Format("lớp <a  href='/Course/Wall/{0}' style='color:green;'>{1}</a>", course.CourseID_u, "" + course.Title_s));
            }
            else
            {
                return MvcHtmlString.Create(string.Format("lớp <a  href='/Course/Wall/{0}' {3}  style='color:green;'>{1}</a>", course.CourseID_u, "" + course.Title_s, onclickHandler));
            }
        }

        /// <summary>
        /// Remove vietnam sign
        /// </summary>
        /// <param name="str">the input string contains vietnam sign</param>
        /// <returns>the input without vietnam sign</returns>
        public static string RemoveVietnameseSigns(string str)
        {
            str = str.Trim();
            string[] arrConvertChars = new string[] { "aAeEoOuUiIdDyY_", "áàạảãâấầậẩẫăắằặẳẵ", "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ", "éèẹẻẽêếềệểễ", "ÉÈẸẺẼÊẾỀỆỂỄ", "óòọỏõôốồộổỗơớờợởỡ",
                "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ", "úùụủũưứừựửữ", "ÚÙỤỦŨƯỨỪỰỬỮ", "íìịỉĩ", "ÍÌỊỈĨ", "đ", "Đ", "ýỳỵỷỹ", "ÝỲỴỶỸ", "!@%^*()+=<>?/,.:;' \"&#[]~$\\" };

            for (int i = 1; i < arrConvertChars.Length; i++)
            {
                for (int j = 0; j < arrConvertChars[i].Length; j++)
                    str = str.Replace(arrConvertChars[i][j], arrConvertChars[0][i - 1]);
            }

            return str;
        }
    }
}